/* 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.shanekjohnson.cmis.client.atompub.service
{
	import org.shanekjohnson.cmis.client.atompub.event.QueryEvent;
	import org.shanekjohnson.cmis.client.atompub.model.Document;
	import org.shanekjohnson.cmis.client.atompub.model.Repository;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	
	import mx.collections.ArrayCollection;

	public class QueryService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://docs.oasis-open.org/ns/cmis/core/200908/";
		private namespace cmisra = "http://docs.oasis-open.org/ns/cmis/restatom/200908/";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        use namespace cmisra;
        
		private var auth:String;
		
		public function QueryService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getQueryResults(repository:Repository, queryStr:String):void 
		{
			var query:XML = 
				<cmis:query xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">
					<cmis:statement>{queryStr}</cmis:statement>
				</cmis:query>;
			
			var request:URLRequest = new URLRequest(repository.queryURL);

			request.data = query;
			request.contentType = "application/cmisquery+xml";
			request.method = URLRequestMethod.POST;
			
			var header:URLRequestHeader;

            header = new URLRequestHeader("Authorization", "Basic " + auth);
            
            request.requestHeaders.push(header);

			var loader:URLLoader = new URLLoader();

			loader.addEventListener(Event.COMPLETE, setQueryResults);
			
			// for logging...
            loader.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
            loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
            loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
            loader.addEventListener(Event.COMPLETE, handleComplete);
 
			loader.load(request); 
		}
		
		private function setQueryResults(event:Event):void 
		{
			var results:ArrayCollection = new ArrayCollection();
			
			var loader:URLLoader = event.target as URLLoader;

			var resultXML:XML = new XML(loader.data);
			
			for each (var d:XML in resultXML.entry)
			{
				results.addItem(Document.getDocument(d));
			}
				
			this.dispatchEvent(new QueryEvent(QueryEvent.RESULTS, results));
		}
		
        private function handleIOError(event:IOErrorEvent):void
        {
            trace ("Load failed: IO error: " + event.text);
        }
        
        private function handleHttpStatus(event:HTTPStatusEvent):void
        {
            trace ("Load failed: HTTP Status = " + event.status);
        }
        
        private function handleSecurityError(event:SecurityErrorEvent):void
        {
            trace ("Load failed: Security Error: " + event.text);
        }
        
        private function handleComplete(event:Event):void
        {
            trace ("The data has successfully been loaded.");
        }

	}
	
}